package com.improve.frame.db.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.improve.frame.db.properties.MybatisPlusAutoFillProperties;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @Description
 *      自定义填充公共字段
 * @Author wzxing918
 * @Date 2021-03-31
 * @Version 1.0.0
 **/
public class DateMetaObjectHandler implements MetaObjectHandler {
    private MybatisPlusAutoFillProperties autoFillProperties;

    public DateMetaObjectHandler(MybatisPlusAutoFillProperties autoFillProperties) {
        this.autoFillProperties = autoFillProperties;
    }

    /**
     * 是否开启了插入填充
     */
    @Override
    public boolean openInsertFill() {
        return autoFillProperties.getEnableInsertFill();
    }

    /**
     * 是否开启了更新填充
     */
    @Override
    public boolean openUpdateFill() {
        return autoFillProperties.getEnableUpdateFill();
    }

    /**
     * 插入填充，字段为空自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Object createTime = getFieldValByName(autoFillProperties.getCreateTimeField(), metaObject);
        Object creator = getFieldValByName(autoFillProperties.getCreatorField(), metaObject);
        Object modifyTime = getFieldValByName(autoFillProperties.getModifyTimeField(), metaObject);
        Object modifier = getFieldValByName(autoFillProperties.getModifierField(), metaObject);

        LocalDateTime localDateTime = LocalDateTime.now();
        if (Objects.isNull(createTime)) {
            setFieldValByName(autoFillProperties.getCreateTimeField(), localDateTime, metaObject);
        }
        if (Objects.isNull(modifyTime)) {
            setFieldValByName(autoFillProperties.getModifyTimeField(), localDateTime, metaObject);
        }
        String currentLoginUser = StringUtils.EMPTY;
        if (Objects.isNull(creator)) {
            setFieldValByName(autoFillProperties.getCreatorField(), currentLoginUser, metaObject);
        }
        if (Objects.isNull(modifier)) {
            setFieldValByName(autoFillProperties.getModifierField(), currentLoginUser, metaObject);
        }
    }

    /**
     * 更新填充
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName(autoFillProperties.getModifyTimeField(), LocalDateTime.now(), metaObject);
        String currentLoginUser = StringUtils.EMPTY;
        setFieldValByName(autoFillProperties.getModifierField(), currentLoginUser, metaObject);
    }
}